import { HttpException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ResponseData } from '../../common/interfaces/result.interface';
import { resError, resSuccess } from '../../common/utils/response.util';
import { CreateMenuDto } from './dto/create-menu.dto';
import { UpdateMenuDto } from './dto/update-menu.dto';
import { Menu } from './menu.entity';
import { treeFilter, listToTree as ltt } from '../../util/treeHelper';
import { listToTree, menuFilter, menuFormat } from '../../util/helper';

@Injectable()
export class MenuService {
  constructor(
    @InjectRepository(Menu) private readonly menuRespository: Repository<Menu>,
  ) {}

  async create(dto: CreateMenuDto) {
    const create = await this.menuRespository.save(dto);
    return create ? resSuccess('创建成功') : resError(200, '创建失败');
  }

  async update(dto: UpdateMenuDto): Promise<ResponseData> {
    const existing = await this.menuRespository.findOne(dto.id);
    if (!existing)
      throw new HttpException(`更新失败，ID 为 ${dto.id} 的菜单不存在`, 404);
    const user: Menu = Object.assign(existing, dto) as Menu;
    const result = await this.menuRespository.update(dto.id, dto);
    if (!result) return resError(200, '菜单信息修改失败');
    return resSuccess('菜单信息修改成功');
  }

  async findAll() {
    const all = await this.menuRespository.find();
    const tree = listToTree(all);
    return resSuccess('查询成功', tree);
  }

  async getTree(user) {
    const { roles } = user;
    const all = await this.menuRespository.find();
    menuFilter(roles, all);
    menuFormat(all);
    return resSuccess('查询成功', listToTree(all));
  }
}
